package com.blb.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 自定义Callable对象
 */
public class MyCallable implements Callable<Long> {
    @Override
    public Long call() throws Exception {
        long sum = 0;
        //长时间运算
        for (int i = 0; i < 100000000L; i++) {
            sum += i;
        }
        System.out.println(Thread.currentThread().getName()+"运算完毕！");
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建FutureTask对象，传入Callable对象
        FutureTask<Long> futureTask = new FutureTask<>(new MyCallable());
        //创建Thread对象，传入FutureTask对象
        Thread thread = new Thread(futureTask);
        //启动线程
        thread.start();
        //获得运算结果
        System.out.println("结果是：" + futureTask.get());
    }
}
